package com.erps.CommonUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UploadPostFiles {
	public List<UploadInfo> UploadFiles = new ArrayList<UploadInfo>();

	private HttpServletRequest request;
	private HttpServletResponse response;
	private static final Logger log = LoggerFactory.getLogger(UploadPostFiles.class);

	public UploadPostFiles(HttpServletRequest aRequest, HttpServletResponse aResponse) {
		request = aRequest;
		response = aResponse;
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		response.setCharacterEncoding("UTF-8");
	}

	public UploadInfo FindField(List<UploadInfo> arList, String cFieldName) {
		UploadInfo aKey = null;
		int iLength = (arList == null) ? 0 : arList.size();
		for (int i = 0; i < iLength; i++) {
			UploadInfo vo = arList.get(i);
			String cKeyName = vo.FileName;
			if (cKeyName.equals(cFieldName)) {
				aKey = vo;
				break;
			}
		}
		return aKey;
	}

	public List<UploadInfo> SavePostFile(String cKeyID) {
		FileUpload f = null;
		List<UploadInfo> arKeys = null;
		ServletContext application = request.getSession().getServletContext();
		String cRootDir = application.getRealPath("/");
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		log.debug("SavePostFile:isMultipart:" + String.valueOf(isMultipart));
		if (isMultipart == true) {
			// Create a factory for disk-based file items
			FileItemFactory factory = new DiskFileItemFactory();
			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			List items;
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e1) {
				e1.printStackTrace();
				log.debug("SavePostFile:isMultipart:" + e1.getMessage());
				return arKeys;
			}
			arKeys = new ArrayList<UploadInfo>();
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {

				} else {
					String cFileName = item.getName();
					if (StringEx.isEmpty(cFileName)) {
						continue;
					}
					UploadInfo aKey = new UploadInfo();
					String cFileID = Sequence.getGuid();
					aKey.ID = cFileID;
					aKey.FileName = item.getFieldName();
					item.getFieldName();
					aKey.ResID = cKeyID;

					String cFileExt = cFileName.substring(cFileName.lastIndexOf("."));
					cFileName = cFileID + cFileExt;
					File fs = new File(cFileName);
					cFileName = fs.getName();
					arKeys.add(aKey);

					String cFileDir = cRootDir + "dfs";
					TextFileUtils.CheckDir(cFileDir);
					String cDayNum = DateUtils.getDayNum();
					cFileDir = cRootDir + "dfs" + File.separatorChar + cDayNum;
					TextFileUtils.CheckDir(cFileDir);
					aKey.Url = "/dfs/" + cDayNum + "/" + cFileName;
					String cFilePath = cFileDir + File.separatorChar + cFileName;
					File uploadedFile = new File(cFilePath);
					if (uploadedFile.exists()) {
						uploadedFile.delete();
					}
					try {
						item.write(uploadedFile);
					} catch (Exception e) {
						e.printStackTrace();
						log.debug("SavePostFile:setFilePath:" + e.getMessage());
					}
				}
			}
		}
		return arKeys;
	}

	public List<String> getUploadSQL(List<UploadInfo> FileList) {
		List<String> sqls = new ArrayList<String>();
		int iLength = (FileList == null) ? 0 : FileList.size();
		JActiveTable aTable = new JActiveTable();
		aTable.setDBTableName("ersp_res_picture");
		aTable.getFields().clear();
		for (int i = 0; i < iLength; i++) {
			UploadInfo rs = FileList.get(i);
			aTable.addFieldValue("id", Sequence.getGuid());
			aTable.addFieldValue("res_id", rs.getResID());
			aTable.addFieldValue("pic_path", rs.getResID());
			aTable.addFieldValue("pic_path", rs.getUrl());
			aTable.addFieldValue("pic_desc", rs.getDesc());
			aTable.addFieldValue("last_update_time", DateUtils.getDayTimeNum());
			sqls.add(aTable.getSQL());
		}
		return sqls;
	}
}
